package com.doxiaopu.students.user.controller;

import com.doxiaopu.students.component.controller.BaseController;
import com.doxiaopu.students.component.result.ResponseResult;
import com.doxiaopu.students.organization.entity.Organization;
import com.doxiaopu.students.user.entity.PersonRelation;
import com.doxiaopu.students.user.entity.User;
import com.doxiaopu.students.user.service.IUserService;
import com.doxiaopu.students.user.vo.OrganizationTypesVO;
import com.doxiaopu.students.user.vo.UserVO;
import com.doxiaopu.students.utils.FtpUtil;
import com.doxiaopu.students.utils.SimpSM2Util;
import com.doxiaopu.students.utils.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@Api(tags = "用户信息")
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    private static final String UPLOAD="\\src\\main\\resources\\static\\images";

    @ApiOperation(value = "用户注册")
    @PostMapping("/reg")
    public ResponseResult<Void> handleReg(User user){
        User data =  userService.reg(user);
        return new ResponseResult<Void>(SUCCESS);
    }

//    @ApiImplicitParam(name = "name",value = "姓名",required = true)
//    @ApiOperation(value = "向客人问好")
//    @GetMapping("/sayHi")
//    public ResponseEntity<String> sayHi(@RequestParam(value = "name")String name){
//        return ResponseEntity.ok("Hi:"+name);
//    }

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public ResponseResult<User> handleLogin(@RequestParam("username") String username, @RequestParam("password") String password,HttpSession session){
        String privateKey = "45b7ac293606cbb505368738e9709e918b782fd8e31a2cfd2bfc0da24573cf4c";
        System.err.print(password);
        String decryptPassword = SimpSM2Util.decrypt(privateKey,password);
        System.err.print("++++decryptPassword:"+decryptPassword);
        User result = userService.login(username,decryptPassword);
        String id = result.getId()+"";
        //生成令牌token
        String token = UUID.randomUUID()+"";
        //存到Redis数据库
        stringRedisTemplate.opsForValue().set(token,id, Duration.ofMinutes(3000L));
        // 将用户名存到session对象中
        session.setAttribute("username",username);
        return new ResponseResult<User>(SUCCESS,token);
    }


    @ApiOperation(value = "获得用户名")
    @GetMapping("/getName")
    public ResponseResult<Object> getName(HttpSession session){
//        String username = "消防";
//        session.setAttribute("username",username);
        Object name = session.getAttribute("username");
        return new ResponseResult<Object>(SUCCESS,"获取成功",name);
    }

    @ApiOperation(value = "获得用户登录信息")
    @GetMapping("/getUserOfLogin")
    public ResponseResult<Void> getUserOfLogin(HttpServletRequest request){
        //获取headers中的参数
        String token = request.getHeader("token");
        System.err.println(token);
        Object id = stringRedisTemplate.opsForValue().get(token);
        System.err.println(id);
        return new ResponseResult<Void>(SUCCESS);
    }
//    private static final String UPLOAD_DIR_NAME="wpload";

    @ApiOperation(value = "用户上传本地图片")
    @PostMapping("/upload")
    @ResponseBody
    public String handleUpload(@ModelAttribute("file") MultipartFile file, HttpSession session ) {
        //确定文件上传的路径
//        String parentPath = session.getServletContext().getRealPath(UPLOAD_DIR_NAME);
//        File parent = new File(parentPath);
//        if(!parent.exists()){
//            parent.mkdirs();
//        }
        //确定文件名
        String originalFileName = file.getOriginalFilename();
        int beginIndex = originalFileName.lastIndexOf(".");
        String suffix = originalFileName.substring(beginIndex);
        String fileName = System.currentTimeMillis()+""+(new Random().nextInt(900000000)+100000000)+suffix;
//        上传图片地址
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath()+UPLOAD;
//        String pre = "http://172.25.96.243:8100";
        //确定文件
        File dest = new File(pre,fileName);
        //执行保存文件
        try {
            file.transferTo(dest);
            System.err.println("上传完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //响应：响应方式与上传无关
        return "/"+fileName;
    }

    @ApiOperation(value = "用户上传OSS服务器文件")
    @PostMapping("/upImg")
    @ResponseBody
    public Object geturl(@ModelAttribute("file") MultipartFile file, HttpSession session) throws IOException {
//        InputStream inputStream = file.getInputStream();
//        //确定文件名
//        String originalFileName = file.getOriginalFilename();
//        int beginIndex = originalFileName.lastIndexOf(".");
//        String suffix = originalFileName.substring(beginIndex);
//        String fileName = System.currentTimeMillis()+""+(new Random().nextInt(900000000)+100000000)+suffix;
//        boolean flag = FtpUtil.uploadFile(fileName,inputStream);
//        return new ResponseResult(SUCCESS,flag);
//
        return UploadUtil.uploadImage(file);

    }

    @ApiOperation(value = "修改用户信息")
    @PostMapping("/changeInfo")
    @ResponseBody
    public ResponseResult<User> changeInfo(HttpServletRequest request,User user){
        Integer id =getUidFromRequest(request);
        user.setId(id);
        System.err.println(user);
        userService.changeInfo(user);
        return new ResponseResult<User>(SUCCESS);
    }

    //    通过id查询用户信息
    @ApiOperation(value = "查询登录用户信息")
    @GetMapping("/GetInfo")
    @ResponseBody
    public ResponseResult<User> GetInfo(HttpServletRequest request){
        if(request != null){
            Integer id =getUidFromRequest(request);
            User data = userService.getInfo(id);
            System.err.print(data);
            data.setPassword(null);
            data.setSalt(null);
            return new ResponseResult<User>(SUCCESS,data);
        }else {
            return new ResponseResult<User>(405);
        }
    }
    //    查询所用的用户信息
    @ApiOperation(value = "查询所有用户信息（手机、用户类型）")
    @PostMapping("/GetAllInfo")
    @ResponseBody
    public ResponseResult<Map<String, Object>> GetAllInfo(UserVO userVO){
        System.err.print(userVO);
        Map<String, Object> data = userService.getAllInfo(userVO.getPhone(),userVO.getTypes(),userVO.getCurrentPage(),userVO.getPageSize());
        return new ResponseResult<Map<String, Object>>(SUCCESS,data);
    }

    //编辑用户的余额
    @ApiOperation(value = "修改用户余额")
    @PostMapping("/updateBalance")
    public ResponseResult<Void> updateBalance(HttpServletRequest request,@RequestParam("TUserId") String TUserId, Integer add,Integer decrease) {
        Integer id =getUidFromRequest(request);
        if(id !=null) {
            Integer row = userService.updateBalanceInfo(TUserId,add,decrease,id);
            if(row == 1) {
                return new ResponseResult<Void>(SUCCESS);
            }else {
                return new ResponseResult<Void>(409,"未更改成功");
            }
        }else {
            return new ResponseResult<Void>(408,"登录过期请重新登录");
        }

    }

    //    查询所有组织成员用户信息
    @ApiOperation(value = "查询所有组织成员用户信息")
    @PostMapping("/getCommunityUserList")
    @ResponseBody
    public ResponseResult<List<User>> getCommunityUserList(HttpServletRequest request){
        Integer id =getUidFromRequest(request);
        if(id !=null) {
            List<User> data = userService.getCommunityUserList(id);
            return new ResponseResult<List<User>>(SUCCESS,data);
        }else {
            return new ResponseResult<List<User>>(408,"登录过期请重新登录");
        }
    }

    //    查询所有组织申请成员用户信息
    @ApiOperation(value = "查询所有组织申请成员用户信息")
    @PostMapping("/getApplyUserList")
    @ResponseBody
    public ResponseResult<List<User>> getApplyUserList(HttpServletRequest request){
        Integer id =getUidFromRequest(request);
        if(id !=null) {
            List<User> data = userService.getApplyCommunityUserList(id);
            return new ResponseResult<List<User>>(SUCCESS,data);
        }else {
            return new ResponseResult<List<User>>(408,"登录过期请重新登录");
        }
    }
    //    会长审核成员
    @ApiOperation(value = "会长审核成员")
    @PostMapping("/updateOrganizationTypes")
    @ResponseBody
    public ResponseResult<Integer> updateOrganizationTypes(HttpServletRequest request, OrganizationTypesVO organizationTypesVO){
        Integer id =getUidFromRequest(request);
        if(id !=null) {
            Integer data = userService.updateOrgTypes(organizationTypesVO,id);
            return new ResponseResult<Integer>(SUCCESS,data);
        }else {
            return new ResponseResult<Integer>(408,"登录过期请重新登录");
        }
    }

    @ApiOperation(value = "创建好友关系")
    @PostMapping("/addPersonRelationship")
    @ResponseBody
    public ResponseResult<Integer> addPersonRelationship(HttpServletRequest request, PersonRelation personRelation) {
        Integer id =getUidFromRequest(request);
        if(id !=null) {
            Integer row = userService.addChatPersonRelation(id,personRelation);
            return new ResponseResult<Integer>(SUCCESS,row);
        }else {
            return new ResponseResult<Integer>(408,"登录过期请重新登录");
        }
    }

    @ApiOperation(value = "查询好友是否存在（已经是好友、不是好友）")
    @PostMapping("/checkFriendsRelation")
    @ResponseBody
    public ResponseResult<String> checkFriendsRelation(HttpServletRequest request, @RequestParam("sendPersonId") String sendPersonId,@RequestParam("acceptPersonId") String acceptPersonId) {
        Integer id =getUidFromRequest(request);
        if(id !=null) {
            String data = userService.checkRecivePsersonId(sendPersonId , acceptPersonId);
            return new ResponseResult<String>(SUCCESS,"请求成功",data);
        }else {
            return new ResponseResult<String>(408,"登录过期请重新登录","");
        }
    }


    private Integer getUidFromRequest(HttpServletRequest request){
        //获取headers中的参数
        String token = request.getHeader("token");
        if(stringRedisTemplate.opsForValue().get(token) != null) {
            return Integer.valueOf(stringRedisTemplate.opsForValue().get(token).toString());
        }else {
            return null;
        }
    }
}
